package com.example.demo.errorAndException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述：统一业务异常处理类
 * @author Ay
 * @date   2017/12/3
 */
@ControllerAdvice(basePackages={"com.example.demo",})
public class GlobalDefaultExceptionHandler {

    /**
     * 业务异常处理
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler({BusinessException.class})
    @ResponseBody   //如果返回的为json数据或其它对象，添加该注解
    public ErrorInfo defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ErrorInfo errorInfo = new ErrorInfo();
        errorInfo.setMessage(e.getMessage());
        errorInfo.setUrl(req.getRequestURI());
        errorInfo.setCode(ErrorInfo.BUSSINESS_ERROR);
        return errorInfo;
    }

    /**
     * 处理请求参数校验异常
     * @param req HttpServletRequest
     * @param e Exception
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public ErrorInfo handleMethodArgumentValid(HttpServletRequest req, Exception e) {
        ErrorInfo errorInfo = new ErrorInfo();
        Integer retCode = 504;
        String  retMsg;
        if (e instanceof MethodArgumentNotValidException) {
            List<String> errorMsgList = new ArrayList<>();
            BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
            if (result.hasErrors()) {
                List<ObjectError> errorList = result.getAllErrors();
                for (ObjectError error : errorList) {
                    errorMsgList.add(String.format("%s",error.getDefaultMessage()));
                }
            }
            retMsg = CollectionUtils.isEmpty(errorMsgList)?null: StringUtils.join(errorMsgList,",");
        } else {
            retMsg = e.getMessage();
        }
        errorInfo.setMessage(retMsg);
        errorInfo.setUrl(req.getRequestURI());
        errorInfo.setCode(retCode);
        return errorInfo;
    }



}
